home *** CD-ROM | disk | FTP | other *** search
/ Games of Daze / Infomagic - Games of Daze (Summer 1995) (Disc 1 of 2).iso / x2ftp / msdos / source / snip9503 / arccrc16.c < prev    next >
C/C++ Source or Header  |  1995-03-14  |  2KB  |  94 lines

  1. /*
  2. ** crc16.c -- calculate 16-bit CRC for file(s)
  3. ** rev. Feb. 1992
  4. ** public domain by Raymond Gardner
  5. **                  Englewood, Colorado
  6. **
  7. ** This program uses the same CRC calculation as ARC (SEA) and LHA (Yoshi)
  8. */
  9.  
  10. #include <stdio.h>
  11. #include <stdlib.h>
  12.  
  13. typedef unsigned short WORD;    /* 'WORD' must be 16-bit unsigned (for crc) */
  14.  
  15. #define bufsiz (16*1024)
  16.  
  17. WORD crc_table[256];
  18.  
  19. /*
  20. ** I determined this function empirically, by examining the
  21. ** table for patterns, and programming via trial-and-error.
  22. ** Don't ask me how it works or if it can be generalized for
  23. ** other CRC polynomials.
  24. */
  25.  
  26. void init_crc_table()
  27. {
  28.       int i, j;
  29.       WORD k;
  30.  
  31.       for (i = 0; i < 256; i++)
  32.       {
  33.             k = 0xC0C1;
  34.             for (j = 1; j < 256; j <<= 1)
  35.             {
  36.                   if (i & j)
  37.                         crc_table[i] ^= k;
  38.                   k = (k << 1) ^ 0x4003;
  39.             }
  40.       }
  41. }
  42.  
  43. /*
  44. ** crc_calc() -- calculate cumulative crc-16 for buffer
  45. */
  46.  
  47. WORD crc_calc(WORD crc, char *buf, unsigned nbytes)
  48. {
  49.       unsigned char *p, *lim;
  50.  
  51.       p = (unsigned char *)buf;
  52.       lim = p + nbytes;
  53.       while (p < lim)
  54.       {
  55.             crc = (crc >> 8 ) ^ crc_table[(crc & 0xFF) ^ *p++];
  56.       }
  57.       return crc;
  58. }
  59.  
  60. void do_file(char *fn)
  61. {
  62.       static char buf[bufsiz];
  63.       FILE *f;
  64.       int k;
  65.       WORD crc;
  66.  
  67.       f = fopen(fn, "rb");
  68.       if (f == NULL)
  69.       {
  70.             printf("%s: can't open file\n", fn);
  71.             return;
  72.       }
  73.       crc = 0;
  74.       while ((k = fread(buf, 1, bufsiz, f)) != 0)
  75.             crc = crc_calc(crc, buf, k);
  76.       fclose(f);
  77.       printf("%-14s %04X\n", fn, crc);
  78. }
  79.  
  80. int main(int argc, char **argv)
  81. {
  82.       int i;
  83.  
  84.       if (argc < 2)
  85.       {
  86.             fprintf(stderr, "Usage: crc filename [filename...]\n");
  87.             return EXIT_FAILURE;
  88.       }
  89.       init_crc_table();
  90.       for (i = 1; i < argc; i++)
  91.             do_file(argv[i]);
  92.       return EXIT_SUCCESS;
  93. }
  94.